package uk.ac.bbk.dcs.muc;

/**
 * Copyright [2011] [Sean Howes and Aruna Gunasekera]
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import java.io.File;
import java.io.FileOutputStream;

import android.os.Environment;
import android.util.Log;

public class FileWritter {

	/***
	 * Attempt to write the provided data to file, if the file or directory does
	 * not exist create it. If does exist delete and replace it.
	 * 
	 * @param data
	 * @param dir
	 * @param filename
	 */
	public static void WriteToFile(String data, String dir, String filename) {
		try {
			File folder = new File(Environment.getExternalStorageDirectory(), dir);
			if (!folder.exists()) {
				folder.mkdir();
			}
			File file = new File(folder.getPath(), filename);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();

			FileOutputStream initialWriter = new FileOutputStream(file, false);

			initialWriter.write(data.getBytes());
			initialWriter.flush();
			initialWriter.close();
		} catch (Exception e) {
			Log.e("writeToFile", "could not write file" + e.getMessage());
		}

	}
}
